<template>
	<view class="pageContent">

		<div class="user-main" v-if="isShow&&isUser">
			<div class="user-top">
				<div class="user-top-item" @click="doubleClick">
					<image class="user-top-img" :src="localImages +'/code.png'" />
					<div class="user-top-name" :style="{'color':0?'#3862AC':'#E7B7C5'}">{{name.substr(4)}}</div>
				</div>
				<div class="user-top-item" @click="getUserPro">
					<image class="user-top-img" :src="[userFlag?localImages +'/user1.png':localImages +'/user0.png']" />
					<div :style="{'color':userFlag?'#3862AC':'#E7B7C5'}">
						{{(userFlag&&userInfo&&userInfo.nickName)?userInfo.nickName.substr(0,4):'用户中心'}}
					</div>
				</div>
				<div class="user-top-item" v-if="1" @click="useAudioAgin">
					<image class="user-top-img"
						:src="[musicFlag?localImages +'/music1.png':localImages +'/music0.png']" />
					<div :style="{'color':musicFlag?'#3862AC':'#E7B7C5'}">{{musicFlag?'背景音乐':'背景音乐'}}</div>
				</div>
				<div class="user-top-item" v-if="0" @click="replenishment">
					<image class="user-top-img" :src="[1?localImages +'/music1.png':localImages +'/music0.png']" />
					<div :style="{'color':1?'#3862AC':'#E7B7C5'}">{{1?'补货入口':'补货入口'}}</div>
				</div>
				<div class="user-top-item" @click="testBlueConnect">
					<image class="user-top-img" :src="[blueFlag?localImages +'/blue1.png':localImages +'/blue0.png']" />
					<div :style="{'color':blueFlag?'#3862AC':'#E7B7C5'}">{{blueFlag?'蓝牙已连接':'蓝牙未连接'}}</div>
				</div>
			</div>
			<swiper class="user-adv" :indicator-dots="false" :autoplay="1">
				<swiper-item v-for="(item,index) in adList" :key="index">
					<image class="user-adv-img" :src="item.dicName" mode="widthFix"></image>
				</swiper-item>
			</swiper>
			<div class="user-goods">
				<div class="user-goods-item" v-if="index<6" v-for="(item,index) in queryGoodsList" :key="index"
					@click="openDoorLimit(index)">
					<div class="user-goods-divimg">
						<image class="user-goods-img" :src="item.imgurl" mode="widthFix"></image>
					</div>
					<div class="user-goods-name">{{item.name ||''}}</div>
					<div class="user-goods-price">￥{{item.price || ''}}</div>
					<template v-if="!item.amount">
						<div class="user-goods-empty">
						</div>
						<div class="user-goods-text">已售完</div>
					</template>
				</div>
				<div class="user-goods-tip">
					<div class="agree-check" @click="checked=!checked">
						<div class="sc-checkbox" :class="{'check' : checked}"></div>
						<span>用户《购买协议及使用说明》</span>
					</div>
					<div>湘ICP备2022002441号</div>
				</div>
			</div>
			<div class="user-code">
				<image class="user-code-img" :src="localImages +'/codeLove.png'" show-menu-by-longpress="true" />
				<div class="user-code-right">
					<div>客官如需更多服务</div>
					<div>请“长按二维码”关注我们在线客服</div>
				</div>
			</div>
			<div class="bottom-enter" v-if="0" @click="replenishEnter">补货入口</div>
			<scModel :show="isModel" :isShowCancel="true" @change="changeModel"></scModel>
		</div>

		<template v-if="isShow&&!isUser">
			<view class="loginM" v-if="!token">
				<image class="loginMIco" :src="images +'/loginMIco.png'" />
				<button class="btOne loginMBt" @click="loginRed">请先验证身份登录</button>
			</view>
			<view class="remote" v-if="token">
				<div class="topPalce">
					<picker @change="periodChange" :range="period" :value="periodIndex" range-key="name">
						<view class="payTypeInput" v-if=" periodId=='' ">所有场地</view>
						<view class="payTypeInput" v-else>
							{{`${period[periodIndex].name}/${period[periodIndex].boxAmount}台`}}
						</view>
						<div class="arrow"></div>
						<!-- <image class="payTypeArrow" src="{{ images + '/down_arrow.png' }}"></image> -->
					</picker>
				</div>
				<view class="remoteMa">
					<view class="remoteMain" @click="selectTap(index)" v-for="(item,index) in emptyList" :key="index">
						<div class="repWorkerOrder-item">
							<span>设备编号</span>
							<span>{{item.imei}}</span>
						</div>
						<div class="repWorkerOrder-item">
							<span>场地名称</span>
							<span>{{item.siteName}}</span>
						</div>
						<div class="repWorkerOrder-item">
							<span>楼层编号</span>
							<span>{{item.position}}</span>
						</div>

						<div class="agoodsName">
							<p v-for="(agoods,index) in item.goods" :key="index" v-if="agoods.name">
								<span>{{agoods.name}}</span>
								<span style="color:#6D92FF;">1</span>
							</p>
						</div>
					</view>
				</view>

				<div class="repWorkerOrder-total" v-if="1">
					<div>
						共补货
						<span>{{totalNumber}}</span> 件
					</div>
					<div class="repToWorker" @click="replenishment" :class="[totalNumber==0?'isActive':'']">去补货</div>
				</div>

			</view>
		</template>


	</view>
</template>

<script>
	import config from '../../static/config.js'
	import util from '../../static/utils/util.js'
	import scModel from '@/components/scModel/scModel.vue'

	export default {
		components: {
			scModel
		},
		data() {
			return {
				images: config.images,
				localImages: config.localImages,
				isUser: config.isUser,
				isShow: false,
				//用户：
				blueFlag: 0,
				userFlag: 0,
				musicFlag: 1,
				adList: [],
				checked: 1,
				queryGoodsList: [],
				name: getApp().globalData.name || "00002122868A",
				count: 0,
				innerAudioContext: '',
				userInfo: '',
				isModel: 0,
				isPaying: false, //是否处于支付状态
				previous: '',
				//补货：
				period: [{
					id: 3,
					name: '3个月'
				}, {
					id: 6,
					name: '6个月'
				}, ],
				periodIndex: 0,
				periodId: '',
				emptyList: [],
				totalNumber: 0,
				token: 0,
				installNum: 0, //总共多少件
				phone: wx.getStorageSync('phone'),

			}
		},
		watch: {
			count: {
				handler(newVal, oldVal) {
					var count = newVal
					this.musicFlag = count > 2 ? false : true
				},
				immediate: true,
			},
		},
		onLoad(query) {
			if(config.isUser){
				var q = decodeURIComponent(query.q) // 获取到二维码原始链接内容
				var scancode_time = parseInt(query.scancode_time) // 获取用户扫码时间 UNIX 时间戳
				console.log('扫描信息:',q,scancode_time)
				util.toast(''+q)
			}
		},
		async onShow() {
			this.isShow = true //页面初始化完成才开始加载页面
			wx.hideTabBar()
			var isUser = this.isUser
			var token = wx.getStorageSync('token')
			var tokenopen = wx.getStorageSync('tokenopen')
			this.token = token
			if (!isUser) {
				wx.showTabBar()
				if (token) {
					this.query()
					this.queryEmpty()
					wx.showTabBar()
				}
			} else {
				var name = wx.getStorageSync('name')
				if (name) {
					this.name = name
				}
				if (tokenopen) {
					this.queryGoods()
				} else {
					getApp().autoLogin().then(() => {
						this.queryGoods()
					})
				}
				this.queryAdvert()
				this.useAudio()
				this.checkUserPro()
				//1.判断是否已经连接成功过设备
				var isConnect = getApp().globalData.isConnect
				if (!isConnect) {
					this.initBLEApp()
				} else {
					console.log('show-isPaying', this.isPaying)
					//2.支付页面返回，不重连设备
					if (this.isPaying) return
					//更新下设备连接状态
					var isConnect = await getApp().testConnectStatus()
					console.log('show-isConnect', isConnect)
				}
			}
		},
		onHide() {
			this.count = 3
			this.musicFlag = false
		},
		methods: {
			//0.3s内双击
			doubleClick() {
				var now = new Date();
				if (now - this.previous < 300) {
					this.onShowModal()
					//this.goTest()
				}
				this.previous = now;
			},
			onShowModal() {
				var that = this;
				wx.showModal({
					title: '开启调试模式',
					content: '',
					cancelColor: "#999999",
					confirmColor: "#E7B7C5",
					confirmText: '确定',
					cancelText: '取消',
					editable:true,
					placeholderText:'请输入调试密码',
					success(res) {
						if (res.confirm) {
							console.log(res.content)
							var content=res.content
							var arr=['3954','0929']
							if(arr.includes(content)) {
								console.log('success',res.content)
								that.goTest()
							}
						} else if (res.cancel) {}
					}
				})
			},

			changeModel() {
				console.log('changeModel')
				this.isModel = false
			},
			async getUserPro() {
				var userInfo = await util.getUserProfile()
				this.userInfo = userInfo
				this.userFlag = true
			},
			checkUserPro() {
				var userInfo = wx.getStorageSync('userInfo')
				if (userInfo) {
					this.userInfo = userInfo
					this.userFlag = true
				}
			},

			useAudioAgin() {
				// 播放中，停止播放
				if (this.musicFlag) {
					// innerAudioContext.stop()
					this.count = 3
				} else {
					this.count = 0
					this.useAudio()
				}
			},
			//播放3次声音
			useAudio() {
				console.log('useAudio=')
				var filePath = '/static/music/miniLove.wav'
				var innerAudioContext = wx.createInnerAudioContext({
					useWebAudioImplement: true,
				})
				this.innerAudioContext = innerAudioContext
				innerAudioContext.src = filePath
				innerAudioContext.onPlay(() => {
					// console.log('innerAudioContext-onPlay')
				})
				innerAudioContext.onError((res) => {
					console.log('innerAudioContext-onError', res)
				})
				innerAudioContext.onEnded(() => {
					++this.count
					console.log('innerAudioContext-onEnded', this.count)
					if (this.count < 3) {
						setTimeout(() => {
							this.useAudio()
						}, 1000)
					}
				})
				innerAudioContext.play() // 播放
			},
			testBlueConnect() {
				util.toast("蓝牙连接中")
				util.tottleOne(() => {
					this.initBLEApp()
				})
			},
			async initBLEApp() {
				var res = await getApp().initBLE()
				console.log('initBLEApp-res', res)
				if (res) {
					//延迟4s查询蓝牙连接状态
					setTimeout(() => {
						var isConnect = getApp().globalData.isConnect
						console.log('initBLEApp-isConnect', isConnect)
						this.blueFlag = isConnect
						//查询电量，提交给后台
						var battery = getApp().globalData.battery
						console.log('initBLEApp-battery', battery)
						if (isConnect && battery) {
							this.boxBattery(battery)
						}
					}, 4000)
				} else {
					// this.isModel=true
				}
			},

			//函数限流2s
			openDoorLimit(index) {
				util.tottleOne(() => {
					this.openDoor(index)
				})
			},
			//开门逻辑
			async openDoor(index) {
				//1数量判断
				var item = this.queryGoodsList[index]
				if (!item.amount) {
					util.toast('已售空')
					return
				}
				//2蓝牙连接判断
				var isConnect = getApp().globalData.isConnect
				if (!isConnect) {
					util.toast('蓝牙未连接')
					return
				}
				//展示加载中
				wx.showLoading({
					title: '',
					duration: 2000
				})
				//3下单前再次连接设备，确保支付后可以开门
				var isConnect = await getApp().testConnectStatus()
				console.log('isConnect=', isConnect)
				if (!isConnect) {
					return
				}
				var door = index + 1
				this.testOrder(door)
				// getApp().testOpenDoor(door)
			},
			//测试生成订单
			async testOrder(door) {
				var url = '/box/prePay'
				var params = {
					boxCode: this.name,
					doorNo: door,
					payType: 1,
					returnUrl: 1,
				}
				var options = {
					url,
					params
				}
				var param = await util.requestPro(options)
				var res = param.result
				//标记为支付状态
				this.isPaying = true
				//根据订单号生成微信支付签名校验信息
				let payJson = JSON.parse(res.payJson);
				var requestPayFlag = await this.requestPay(payJson)
				console.log('requestPayFlag=', requestPayFlag)
				//延迟0.5s后关闭支付状态
				setTimeout(() => {
					this.isPaying = false
				}, 500)
				if (requestPayFlag || 0) {
					this.queryGoods()
					console.log('支付成功,准备开门')
					var openDoorFlag = await getApp().testOpenDoor(door)
					//开门成功，然后刷新下商品列表
					console.log('openDoorFlag=', openDoorFlag)
					if (openDoorFlag) {}
				}
			},
			//微信支付
			requestPay(payJson) {
				var self = this;
				return new Promise((resolve, reject) => {
					wx.requestPayment({
						timeStamp: payJson.timeStamp,
						nonceStr: payJson.nonceStr,
						package: payJson.package,
						signType: payJson.signType,
						paySign: payJson.paySign,
						success(res) {
							console.log('支付成功', res);
							wx.showToast({
								title: '支付成功',
								icon: 'none',
								duration: 1000,
							});
							resolve(true)
						},
						fail(res) {
							console.log('fail', res);
							wx.showToast({
								title: '取消支付',
								icon: 'none'
							});
							resolve(false)
						},
						complete(res) {},
					});
				})

			},

			testEmptyList() {
				var item = {
					"id": 4894,
					"imei": "6513657745",
					"siteName": "深圳测试",
					"goods": [{
						"name": "情趣内衣均码1套，款式随机",
						"supplier": "湖南长沙",
						"amount": 0,
						"boxId": 4894,
						"doorNo": 1
					}]
				}
				this.emptyList[0] = item
			},
			periodChange(e) {
				// console.log('periodChange', e)
				var value = e.detail.value;
				var id = this.period[value].id
				console.log('periodChange', value, id)
				this.periodIndex = value
				this.periodId = id
				this.queryEmpty()
			},
			// 电量提交
			async boxBattery(battery) {
				var url = '/box/battery'
				var params = {
					code: this.name,
					battery: battery
				}
				var options = {
					url,
					params
				}
				var param = await util.requestPro(options)
			},
			// 首页广告
			async queryAdvert() {
				var url = '/dict/query'
				var params = {
					dicType: 'Advert'
				}
				var options = {
					url,
					params
				}
				var param = await util.requestPro(options)
				this.adList = param.result
				// console.log('this.queryAdvert', this.adList)
			},
			// 查询场地设备
			async query() {
				var url = '/agent/site/query'
				var params = {

				}
				var options = {
					url,
					params
				}
				var param = await util.requestPro(options)
				this.period = param.result
				//添加所有场地选择项
				var lastItem = {
					"id": "",
					"name": "所有场地",
				}
				this.period.push(lastItem)
				console.log('this.period', this.emptyList)
			},
			// 查询场地设备
			async queryGoods() {
				var url = '/box/queryGoods'
				// var code = "4280046158"
				var code = this.name
				var params = {
					code
				}
				var options = {
					url,
					params,
				}
				try {
					var param = await util.requestPro(options)
					this.queryGoodsList = param.result
					console.log('queryGoods', param)
				} catch (e) {
					this.queryGoodsList = []
				}


			},

			// 查询待补货
			async queryEmpty() {
				var url = '/agent/boxadmin/queryEmpty'
				var params = {
					siteId: this.periodId
				}
				var options = {
					url,
					params
				}
				var param = await util.requestPro(options)
				var result = param.result
				this.emptyList = result
				let num = 0
				if (result.length) {
					result.forEach(item => {
						num += item.goods.length;
					})
				}
				this.totalNumber = num
			},

			replenishment() {
				uni.navigateTo({
					url: '/pages/index/replenishmentList'
				})
			},

			selectTap(index) {
				switch (index) {
					case 0:
						wx.navigateTo({
							url: '/pages/index/install'
						})
						break;
					case 1:
						wx.navigateTo({
							url: '/pages/index/myOrder'
						})
						break;
					case 2:
						wx.navigateTo({
							url: '/pages/index/deviceManager'
						})
						break;
					default:
						break;
				}
			},
			loginRed() {
				uni.redirectTo({
					url: '/pages/index/login1'
				})
			},
			goTest() {
				uni.navigateTo({
					url: '/pages/index/test'
				})
			},
			replenishEnter() {
				this.loginRed()
			},
		},

	}
</script>

<style lang="scss">
	$color1:#E7B7C5;
	$color2:#3862AC;

	.pageContent {}

	.user-main {
		min-height: 100vh;
		width: 100%;
		background: #fff;
		padding-bottom: 66rpx;
	}

	.user-top {
		display: flex;
		padding: 20rpx 20rpx 0rpx 20rpx;
		justify-content: space-between;
	}

	.user-top-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 158rpx;
		/* border: 1px solid #666; */
	}

	.user-top-img {
		width: 48rpx;
		height: 48rpx;
	}

	.user-top-name {
		white-space: nowrap;
	}

	/* 此处设置180rpx,图片后面做适配 */
	.user-adv {
		display: flex;
		position: relative;
		height: 180rpx;
		margin-top: 20rpx;
		overflow: hidden;
		border: 1rpx solid transparent;
	}

	.user-adv-img {
		height: 100%;
		width: 100%;
		border: 1rpx solid #123;
	}

	.user-goods {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-around;
		background: #E7B7C5;
		padding: 20rpx 0rpx 20rpx 0rpx;
	}

	.user-goods-item {
		position: relative;
		display: flex;
		flex-direction: column;
		width: 48%;
		border-radius: 10rpx;
		background: #fff;
		margin-bottom: 10rpx;
		padding: 10rpx 20rpx 10rpx 20rpx;
		border: 1rpx solid transparent;
	}

	.user-goods-divimg {
		height: 330rpx;
		/* border: 1rpx solid #f00; */
		/* margin: auto; */
	}

	.user-goods-img {
		/* display: flex; */
		width: 100%;
		height: 99%;
		/* border: 1rpx solid #3862AC; */
	}

	.user-goods-name {
		color: #3862AC;
	}

	.user-goods-price {
		margin-top: 10rpx;
		color: #f00;
	}

	.user-goods-tip {
		display: flex;
		color: #fff;
		width: 100%;
		justify-content: space-between;
		padding: 0rpx 10rpx 0rpx 10rpx;
		line-height: 48rpx;
		// border: 1rpx solid #789;
	}

	.user-goods-empty {
		position: absolute;
		top: -2rpx;
		left: -2rpx;
		right: -2rpx;
		bottom: -2rpx;
		background: #333;
		border-radius: 10rpx;
		opacity: 0.5;

	}

	.user-goods-text {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%) rotate(25deg);
		color: $color1;
		opacity: 1;
		font-size: 50rpx;
		font-style: italic;
	}

	.agree-check {
		position: relative;
		display: inline-block;

		// border: 1px solid;
		.sc-checkbox {
			position: relative;
			transform: scale(0.8);
		}

		.sc-checkbox:before {
			border: 2rpx solid #fff;
		}

		.sc-checkbox.check:before {
			border-color: #fff;
			background-color: #fff;
		}

		.sc-checkbox.check:after {
			border-left: 8rpx solid $color1;
			border-bottom: 8rpx solid $color1;
		}

		text {
			color: #030303;
		}
	}

	.user-code {
		position: fixed;
		display: flex;
		bottom: 0rpx;
		left: 0;
		width: 100%;
		background: #fff;
		padding: 10rpx 10rpx 10rpx 50rpx;
		z-index: 99;

		.user-code-img {
			display: inline-block;
			width: 110rpx;
			height: 110rpx;
		}

		.user-code-right {
			color: $color2;
			padding: 10rpx 0rpx 10rpx 20rpx;
		}
	}

	.bottom-enter {
		position: fixed;
		bottom: 80rpx;
		right: 0;
		height: 80rpx;
		width: 160rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-shadow: 0 -6px 4px -4px rgba(0, 85, 255, 0.1);
		font-size: 30rpx;
		background: $color2;
		color: $color1;
		padding-left: 20rpx;
		border-radius: 20rpx 0rpx 0rpx 20rpx;

		z-index: 999;
	}


	/***** 补货员页面 *****/
	.loginM {
		position: relative;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 250rpx 0rpx 0rpx 0rpx;
	}

	.loginMIco {
		width: 240rpx;
		height: 270rpx;
	}

	.loginMBt {
		width: 70%;
		margin: 50rpx 0rpx 0rpx 0rpx;
		background: $color2;
	}

	.remote {
		/* text-align: center; */
	}


	.topPalce,
	.remoteMain {
		/* width: 120rpx; */
		/* height: 120rpx; */
		background: #fff;
		border-radius: 10rpx;
		box-shadow: 0px 3px 3px 0px rgba(114, 96, 255, 0.1);
		font-size: 30rpx;
		padding: 10rpx 20rpx 0rpx 20rpx;
		margin: 0rpx 30rpx 30rpx 30rpx;
		/* border: 1px solid #666; */
	}

	.topPalce {
		padding: 20rpx 20rpx 20rpx 0rpx;
		margin-top: 20rpx;
	}

	.payTypeInput {
		padding-left: 20rpx;
		font-size: 32rpx;
		border-left: 8rpx solid #6d92ff;
	}

	.remoteMa {
		padding: 10rpx 0rpx 0rpx 0rpx;
		/* border: 1px solid #f00; */
	}

	.arrow {
		float: right;
		margin-top: -32rpx;
		margin-right: 16rpx;
		width: 28rpx;
		height: 28rpx;
	}

	.repWorkerOrder-item {
		height: 58rpx;
		display: flex;
		align-items: center;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.repWorkerOrder-item>span:first-child {
		margin-right: 20rpx;
	}

	.agoodsName>p {
		display: flex;
		justify-content: space-between;
		padding: 10rpx 0rpx 10rpx 0rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.repWorkerOrder-total {
		position: fixed;
		bottom: 0;
		left: 0;
		height: 100rpx;
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;
		background: #fff;
		box-shadow: 0 -6px 4px -4px rgba(0, 85, 255, 0.1);
		font-size: 30rpx;
		z-index: 99;
	}


	.repWorkerOrder-total>div:nth-child(1) {
		margin-left: 50rpx;
	}

	.repToWorker {
		display: flex;
		align-items: center;
		height: 100%;
		background: #6d92ff;
		color: #fff;
		margin-left: auto;
		padding: 0rpx 50rpx;
	}

	.repToWorker.isActive {
		background-color: #979eb2 !important;
		color: #5c616d !important;
	}
</style>
